<template>
  <div class="app-container">

    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="top" label-width="100%">

      <el-card>
        <el-form-item label="科目名称" prop="name">
          <el-input v-model="postForm.name" />
        </el-form-item>
      </el-card>

      <div style="margin-top: 20px">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="info" @click="routeBack">返回</el-button>
      </div>

    </el-form>

  </div>
</template>

<script>
import request from '@/request'

export default {
  name: 'SubjectForm',
  data() {
    return {
      postForm: { },
      rules: {
        name: [ { required: true, message: '科目名称不能为空！' } ] 
      }
    }
  },
  created() {
    const id = this.$route.params.id
    if (typeof id !== 'undefined') {
      request({ method: 'post', url: '/subject/query', 
        data: { current: 1, size: 1, params: {id} }
      })
      .then(resp=>{ 
        this.postForm = resp.data.data.records[0]
      })
    }
  },
  methods: {
    submitForm() {
      console.log(JSON.stringify(this.postForm))

      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return
        }

        var url = `/subject/${this.postForm.id?'update':'add'}`
        var data = this.postForm.id? this.postForm: {
          id: null, name: this.postForm.name, questions: null
        }
        request({ method: 'post', url, data })
        .then(resp=>{ 
          this.$notify({
            title: '成功',
            message: '题库保存成功！',
            type: 'success',
            duration: 2000
          })
          this.routeBack()
        })

      })
    },

    routeBack() {
      this.$router.push({ name: 'Subjects' })
    }

  }
}
</script>
